import React, { useState, useEffect } from 'react';
import { Table, Button, Modal, Form, Input, Select, Tree, message, Divider, Checkbox } from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined, SearchOutlined, UsergroupAddOutlined } from '@ant-design/icons';
import { getRoles, createRole, updateRole, deleteRole, getMenus } from '../../services/api';

const { Option } = Select;
const { TreeNode } = Tree;
const { Group } = Checkbox;

const RoleConfig = () => {
  const [roles, setRoles] = useState([]);
  const [menus, setMenus] = useState([]);
  const [loading, setLoading] = useState(false);
  const [visible, setVisible] = useState(false);
  const [editMode, setEditMode] = useState(false);
  const [currentRole, setCurrentRole] = useState({});
  const [form] = Form.useForm();
  const [searchText, setSearchText] = useState('');
  const [menuTreeData, setMenuTreeData] = useState([]);
  const [checkedKeys, setCheckedKeys] = useState([]);

  useEffect(() => {
    fetchRoles();
    fetchMenus();
  }, []);

  const fetchRoles = async () => {
    setLoading(true);
    try {
      const data = await getRoles();
      setRoles(data);
    } catch (error) {
      message.error('获取角色列表失败');
      console.error('Failed to fetch roles:', error);
    }
    setLoading(false);
  };

  const fetchMenus = async () => {
    try {
      const data = await getMenus();
      setMenus(data);
      const formattedTreeData = formatTreeData(data);
      setMenuTreeData(formattedTreeData);
    } catch (error) {
      message.error('获取菜单列表失败');
      console.error('Failed to fetch menus:', error);
    }
  };

  // 格式化菜单数据为树结构
  const formatTreeData = (data, parentId = 0) => {
    return data
      .filter(item => item.parentId === parentId)
      .map(item => {
        const children = formatTreeData(data, item.id);
        return {
          title: item.name,
          key: item.id,
          ...item,
          children: children.length > 0 ? children : undefined
        };
      });
  };

  const handleAdd = () => {
    setEditMode(false);
    setCurrentRole({});
    setCheckedKeys([]);
    form.resetFields();
    setVisible(true);
  };

  const handleEdit = (role) => {
    setEditMode(true);
    setCurrentRole(role);
    setCheckedKeys(role.menuIds || []);
    form.setFieldsValue(role);
    setVisible(true);
  };

  const handleDelete = async (id) => {
    try {
      await deleteRole(id);
      message.success('删除角色成功');
      fetchRoles();
    } catch (error) {
      message.error('删除角色失败');
      console.error('Failed to delete role:', error);
    }
  };

  const handleSubmit = async (values) => {
    try {
      // 添加选中的菜单ID
      const submitValues = { ...values, menuIds: checkedKeys };

      if (editMode) {
        await updateRole(currentRole.id, submitValues);
        message.success('更新角色成功');
      } else {
        await createRole(submitValues);
        message.success('创建角色成功');
      }
      setVisible(false);
      fetchRoles();
    } catch (error) {
      message.error(editMode ? '更新角色失败' : '创建角色失败');
      console.error('Failed to submit role:', error);
    }
  };

  // 递归渲染树节点
  const renderTreeNodes = data =>
    data.map(item => {
      if (item.children) {
        return (
          <TreeNode title={item.name} key={item.id} dataRef={item}>
            {renderTreeNodes(item.children)}
          </TreeNode>
        );
      }
      return <TreeNode title={item.name} key={item.id} dataRef={item} />;
    });

  const filteredRoles = roles.filter(role =>
    role.name.toLowerCase().includes(searchText.toLowerCase()) ||
    role.description.toLowerCase().includes(searchText.toLowerCase())
  );

  // 获取角色拥有的菜单名称
  const getRoleMenuNames = (menuIds) => {
    if (!menuIds || menuIds.length === 0) return '无';
    return menuIds
      .map(id => {
        const menu = menus.find(m => m.id === id);
        return menu ? menu.name : '';
      })
      .filter(name => name)
      .join(', ');
  };

  const columns = [
    { title: 'ID', dataIndex: 'id', key: 'id' },
    { title: '角色名称', dataIndex: 'name', key: 'name' },
    { title: '描述', dataIndex: 'description', key: 'description' },
    { title: '拥有菜单', dataIndex: 'menuIds', key: 'menuIds', render: getRoleMenuNames },
    { title: '状态', dataIndex: 'status', key: 'status', render: status => (
      <span style={{ color: status === 'active' ? 'green' : 'red' }}>
        {status === 'active' ? '启用' : '禁用'}
      </span>
    )},
    { title: '操作', key: 'action', render: (_, record) => (
      <div>
        <Button
          type="primary"
          icon={<EditOutlined />}
          size="small"
          style={{ marginRight: 8 }}
          onClick={() => handleEdit(record)}
        >
          编辑
        </Button>
        <Button
          type="danger"
          icon={<DeleteOutlined />}
          size="small"
          onClick={() => handleDelete(record.id)}
        >
          删除
        </Button>
      </div>
    )}
  ];

  return (
    <div className="role-config">
      <div className="header">
        <h2>角色配置</h2>
        <div className="search-bar">
          <Input
            placeholder="搜索角色名称或描述"
            prefix={<SearchOutlined />}
            value={searchText}
            onChange={e => setSearchText(e.target.value)}
          />
          <Button type="primary" icon={<PlusOutlined />} onClick={handleAdd}>
            新增角色
          </Button>
        </div>
      </div>

      <Table
        columns={columns}
        dataSource={filteredRoles}
        loading={loading}
        rowKey="id"
        pagination={{ pageSize: 10 }}
      />

      <Modal
        title={editMode ? '编辑角色' : '新增角色'}
        visible={visible}
        onOk={form.submit}
        onCancel={() => setVisible(false)}
        width={800}
      >
        <Form form={form} layout="vertical" onFinish={handleSubmit}>
          <Form.Item
            name="name"
            label="角色名称"
            rules={[{ required: true, message: '请输入角色名称' }]}
          >
            <Input placeholder="请输入角色名称" />
          </Form.Item>

          <Form.Item name="description" label="描述">
            <Input.TextArea placeholder="请输入角色描述" />
          </Form.Item>

          <Form.Item name="status" label="状态" rules={[{ required: true, message: '请选择状态' }]}>
            <Select placeholder="请选择状态">
              <Option value="active">启用</Option>
              <Option value="inactive">禁用</Option>
            </Select>
          </Form.Item>

          <Divider>
            <UsergroupAddOutlined /> 权限配置
          </Divider>

          <Form.Item label="菜单权限">
            <Tree
              checkable
              showLine
              defaultExpandAll
              onCheck={keys => setCheckedKeys(keys)} 
              checkedKeys={checkedKeys}
            >
              {renderTreeNodes(menuTreeData)}
            </Tree>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default RoleConfig;